﻿using Newtonsoft.Json;

namespace D.UtilCore.Dtos
{
    /// <summary>API调用结果（泛型集合）</summary>
    public class ApiListResult<T> : ApiBaseResult<T>
    {
        private IList<T> data;

        /// <summary>参数有误</summary>
        public static readonly ApiListResult<T> ParamError =
            new ApiListResult<T>() { Code = StatusCodeEnum.Params, Msg = "参数有误" };

        [JsonProperty("total")]
        public int Total = 0;

        /// <summary>构造函数</summary>
        public ApiListResult()
        { Code = StatusCodeEnum.OK; }

        /// <summary>构造函数</summary>
        /// <param name="code">应答码（约定：200-成功、500-失败或出错、其它-按需约定）</param>
        public ApiListResult(StatusCodeEnum code)
        { Code = code; }

        /// <summary>应答数据，非null</summary>
        [JsonProperty("data")]
        public virtual IList<T> Data
        {
            get
            {
                if (data == null) { data = new List<T>(); }
                return data;
            }
            set { data = value; }
        }

        /// <summary>生成成功时的应答实例</summary>
        /// <param name="message">应答消息</param>
        /// <param name="data">应答数据</param>
        /// <returns>ApiListResult&lt;T&gt; 实例</returns>
        public static ApiListResult<T> Success(IList<T> data, int total = 0, string message = "success")
        {
            return new ApiListResult<T> { Code = StatusCodeEnum.OK, Data = data, Total = total == 0 ? data.Count : total, Msg = message };
        }

        /// <summary>生成失败时的应答实例</summary>
        /// <param name="message"></param>
        /// <returns>ApiListResult&lt;T&gt; 实例</returns>
        public static ApiListResult<T> Fail(string message = "fail")
        {
            return new ApiListResult<T> { Code = StatusCodeEnum.Error, Msg = message };
        }
    }

}
